package commonutil

import (
	"github.com/google/uuid"
	"log"
	"runtime"
	"strings"
	"syscall"
	"unsafe"
)

func ThrowIfNeed(err error) {
	if err != nil {
		log.Panicln(err)
	}
}

func GetLineSep() string {
	if "windows" == runtime.GOOS {
		return "\r\n"
	}
	return "\n"
}

func ReplOsLineSep(str string) string {
	return strings.TrimSpace(strings.ReplaceAll(strings.ReplaceAll(str, "\r", ""), "\n", GetLineSep()))
}

// SyscallSucc 判断syscall调用是否成功
// syscall正常情况下会返回：The operation completed successfully.通过判断其中包含success来判断
func SyscallSucc(err error) bool {
	if nil != err {
		if strings.Contains(err.Error(), "success") {
			return true
		}
	}
	return false
}

func GetUuid() string {
	return strings.ToLower(strings.ReplaceAll(uuid.NewString(), "-", ""))
}

// GetSyscallUtf16Str 把syscall返回的LPWSTR转换为go的字符串
// 利用c语言字符串末尾的\0作为判断结束的标识
func GetSyscallUtf16Str(ptr uintptr) string {
	if 0 == ptr {
		return ""
	}
	p := unsafe.Pointer(ptr)
	array := make([]uint16, 0, 20)
	for {
		var pchar *uint16 = (*uint16)(p)
		// 遇到字符串结尾的\0，表示字符串结束
		if 0 == *pchar {
			break
		}
		array = append(array, *pchar)
		p = unsafe.Add(p, 2)
	}
	return syscall.UTF16ToString(array)
}
